import { defineStore } from "pinia";
import {getCartApi,addCartApi,updateCartApi,delCartApi} from '@/server'

const useCartStore=defineStore('cart',{
  state:()=>({
    cartList:JSON.parse(localStorage.getItem('cartList'))
  }),
  actions:{
    // 获取购物车数据
    async getCart(params){
      let res=await getCartApi(params)
      res.data.result.forEach(ele => {
        ele.isChecked=false
      });
      this.cartList=res.data.result
      localStorage.setItem('cartList',JSON.stringify(res.data.result))
    },
    // 添加购物车数据
    async addCart(data){
      await addCartApi(data)
      this.getCart()
    },
    // 修改购物车数据
    async updateCart(id,data){
      await updateCartApi(id,data)
      this.getCart()
    },
    // 删除购物车数据
    async delCart(id){
      await delCartApi(id)
      this.getCart()
    }
  },
})
export default useCartStore